package com.baosight.risk.service.xtzy.impl;

import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.workflow.AfterHandler;
import com.baosight.risk.api.workflow.UpdateHandler;
import com.baosight.risk.api.xtzy.IXtzyCompanyService;
import com.baosight.risk.api.xtzy.IXtzyUserPermissionService;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.aspects.factory.AsyncFactory;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.constant.CommonConstant;
import com.baosight.risk.common.manager.AsyncManager;
import com.baosight.risk.common.utils.DateUtils;
import com.baosight.risk.common.utils.ShiroUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.xtzy.XtzyRoleUserMapper;
import com.baosight.risk.mapper.xtzy.XtzyUserPermissionMapper;
import com.baosight.risk.service.fltd.vo.FltdTaskVO;
import com.baosight.risk.service.riim.entity.RiimRiskImport;
import com.baosight.risk.service.riim.vo.RiimRiskImportVO;
import com.baosight.risk.service.rire.entity.RireRiskWarningStatus;
import com.baosight.risk.service.rire.vo.RiskWarningStatusVO;
import com.baosight.risk.service.system.entity.SysOperLog;
import com.baosight.risk.service.xtzy.entity.XtzyCompany;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import com.baosight.risk.service.xtzy.entity.XtzyUserPermission;
import com.baosight.risk.service.xtzy.vo.XtzyUserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 类 名: XtzyUserServiceImpl
 * 描 述:
 * 作 者: 黄鑫
 * 创 建：2022年09月05日
 * 版 本：v2.2.0
 * 历 史: (版本) 作者 时间 注释
 */
@Slf4j
@Service
public class XtzyUserPermissionServiceImpl extends BaseServiceImpl<XtzyUserPermission> implements IXtzyUserPermissionService, UpdateHandler, AfterHandler {

    @Autowired
    private XtzyUserPermissionMapper userPermissionMapper;

    @Autowired
    private FltdProcessService fltdProcessService;

    @Autowired
    private IXtzyCompanyService xtzyCompanyService;

    @Autowired
    private XtzyRoleUserMapper XtzyRoleUserMapper;




    @Override
    public List<XtzyUserPermission> selectUserPermissionList(XtzyUserPermission userPermission) {
        List<XtzyUserPermission> list = new ArrayList<XtzyUserPermission>();
        XtzyUser user=ShiroUtils.getUser();
        servicePage();
        List<XtzyUserVO> userRole=XtzyRoleUserMapper.selectRoleByUserCode(user.getUserCode());
        if (user.isAdmin() || userRole.stream().anyMatch(m->m.getRoleKey().equals("RISK03"))) {
            list =  userPermissionMapper.selectPermissionData(userPermission);
        }else{
            userPermission.setApplyUserCode(user.getUserCode());
            list = userPermissionMapper.selectPermissionData(userPermission);
        }
        return list;
    }


    @Override
    public Integer savePermissionUser(XtzyUserPermission userPermission) {

        if(StringUtils.isNotEmpty(userPermission.getId())){
            XtzyUserPermission updatePermission=new XtzyUserPermission();
            BeanUtils.copyBeanProp(updatePermission,userPermission);
            updatePermission =(XtzyUserPermission) BeanUtils.updateBean(updatePermission);
            userPermissionMapper.updateByPrimaryKey(updatePermission);

        }else{
            XtzyUser user=ShiroUtils.getUser();
            userPermission =(XtzyUserPermission) BeanUtils.initBean(userPermission);
            userPermission.setApplyUserCode(user.getUserCode());
            userPermission.setApplyUserName(user.getUserDesc());
            List<XtzyCompany> companyList=xtzyCompanyService.getCompany(user.getUserCode());
            if(CollectionUtils.isNotEmpty(companyList)) {
                userPermission.setStatus(CommonConstant.AUTH_APPLY_STATUS_CODE.AUTH_APPLY_STATUS_01);
                userPermission.setStatusName(CommonConstant.AUTH_APPLY_STATUS_NAME.AUTH_APPLY_STATUS_NAME_APPROVAL);
                userPermission.setCompCode(companyList.get(0).getCompCode());
                userPermission.setCompName(companyList.get(0).getCompName());
                userPermission.setManageCompCode(user.getManageCompCode());
                userPermission.setManageCompName(user.getManageCompName());
            }
            userPermissionMapper.insert(userPermission);

        }
        return 1;

    }

    @Override
    public XtzyUserPermission selectByPermissionUser(String id) {
        XtzyUserPermission param = new XtzyUserPermission();
        param.setId(id);
        return userPermissionMapper.selectOne(param);
    }

    /**
     * status	当前节点状态
     * nextStatus	下一节点状态
     * nextStatusName	下一节点状态名称
     * acctYear	当前年度
     * quarterCurrent	当前季度
     * deptCode	填报人的部门编码
     * bizGuid 业务id
     * taskGuid 项目id(重点风险id)
     * context 审批意见
     * submitType 提交、回退、结束, 值：(submit, reject, end)
     *
     * @param params
     */
    @Override
    public boolean updateStatus(Map<String, Object> params) {
        /*XtzyUserPermission status = new XtzyUserPermission();
        String id = (String) params.get("bizGuid");
        String planStatus = (String) params.get("nextStatus");
        String planStatusName = (String) params.get("nextStatusName");
        status = (XtzyUserPermission) BeanUtils.updateBean(status);
        status.setId(id);
        status.setStatus(planStatus);
        status.setStatusName(planStatusName);
        userPermissionMapper.updateByPrimaryKeySelective(status);*/
        return true;
    }

    /**
     * 权限申请提交待办
     */
    @Override
    public void submitUserPermission(XtzyUserPermission userPermission) throws Exception {
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;
        XtzyUser user=ShiroUtils.getUser();
        userPermission =(XtzyUserPermission) BeanUtils.initBean(userPermission);
        userPermission.setApplyUserCode(user.getUserCode());
        userPermission.setApplyUserName(user.getUserDesc());
        List<XtzyCompany> companyList=xtzyCompanyService.getCompany(user.getUserCode());
        if(CollectionUtils.isNotEmpty(companyList)) {
            userPermission.setStatus(CommonConstant.AUTH_APPLY_STATUS_CODE.AUTH_APPLY_STATUS_01);
            userPermission.setStatusName(CommonConstant.AUTH_APPLY_STATUS_NAME.AUTH_APPLY_STATUS_NAME_APPROVAL);
            userPermission.setCompCode(companyList.get(0).getCompCode());
            userPermission.setCompName(companyList.get(0).getCompName());
            userPermission.setManageCompCode(user.getManageCompCode());
            userPermission.setManageCompName(user.getManageCompName());
        }
        userPermissionMapper.insert(userPermission);
        this.doSubmit(userPermission);

        // 保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }

    }


    private void doSubmit(XtzyUserPermission userPermission) throws Exception {
        Exception error = null;
        try {
            FltdTaskVO taskVO = new FltdTaskVO();
            taskVO.setFlowNo("quanxian");
            taskVO.setFlowName("权限申请");
            taskVO.setBizName("权限申请");
            taskVO.setBizDesc("权限申请");
            taskVO.setAcctYear(DateUtils.format(new Date(), "yyyy"));
            taskVO.setQuarterCode(DateUtils.getQuarter(new Date()));
            taskVO.setQuarterName(DateUtils.getQuarterName(taskVO.getQuarterCode()));


            taskVO.setCompCode(userPermission.getCompCode());
            taskVO.setCompName(userPermission.getCompName());
            XtzyCompany company = new XtzyCompany();
            company.setCompCode(userPermission.getCompCode());
            company.setCompName(userPermission.getCompName());
            taskVO.setCustomCompany(company);
            taskVO.setCurrUserCode(userPermission.getCheckUserCode());
            taskVO.setCurrUserName(userPermission.getCheckUserName());
            taskVO.setBizName(userPermission.getApplyTypeName());
            taskVO.setManageCompCode(userPermission.getManageCompCode());
            taskVO.setManageCompName(userPermission.getManageCompName());
            String bizDesc = "<" + userPermission.getApplyTypeName() + ">" + "申请";
            taskVO.setBizDesc(bizDesc);
            taskVO.setBizGuid(userPermission.getId());
            taskVO.setGroupCondition(taskVO.getAcctYear() + taskVO.getQuarterCode());
            try {
                fltdProcessService.doStart(taskVO);
                // 保存日志到数据库
                AsyncManager.me().execute(AsyncFactory.recordOper(
                        fltdProcessService.getLog("权限申请-流程启动成功", 0, "业务id：" + userPermission.getId() + "，权限申请id：" + userPermission.getId(), null)));
            } catch (Exception e) {
                // 保存日志到数据库
                AsyncManager.me().execute(AsyncFactory.recordOper(
                        fltdProcessService.getLog("权限申请-流程启动失败", 1, "业务id：" + userPermission.getId() + "，权限申请id：" + userPermission.getId() + ", 失败原因：" + e.getMessage(), null)));
                error = e;
            }
        } catch (Exception e) {
            // 保存日志到数据库
            AsyncManager.me().execute(AsyncFactory.recordOper(
                    fltdProcessService.getLog("权限申请-下发异常", 1, e.getMessage(), null)));
            error = e;
        }
        if (error != null) {
            throw error;
        }
    }

    /**
     * status	当前节点状态
     * nextStatus	下一节点状态
     * nextStatusName	下一节点状态名称
     * acctYear	当前年度
     * quarterCurrent	当前季度
     * deptCode	填报人的部门编码
     * bizGuid 业务id
     * taskGuid 项目id(重点风险id)
     * context 审批意见
     * submitType 提交、回退、结束, 值：(submit, reject, end)
     */
    @Override
    public boolean doAfter(Map<String, Object> params) {
        try {
            //根据biz_guid 查询重点风险披露报告表（T_RIRE_RISK_WARNING_STATUS）获取管理单位、年度、季度
            XtzyUserPermission param=new XtzyUserPermission();
            param.setId(params.get("bizGuid").toString());
            XtzyUserPermission userPermission = userPermissionMapper.selectOne(param);
            if(!ObjectUtils.isEmpty(userPermission)){

                if(CommonConstant.AUTH_APPLY_STATUS_CODE.AUTH_APPLY_STATUS_01.equals(userPermission.getApprovalStatus())){
                    userPermission.setStatus(CommonConstant.AUTH_APPLY_STATUS_CODE.AUTH_APPLY_STATUS_05);
                    userPermission.setStatusName(CommonConstant.AUTH_APPLY_STATUS_NAME.AUTH_APPLY_STATUS_NAME_SUBMIT);
                }
                if(CommonConstant.AUTH_APPLY_STATUS_CODE.AUTH_APPLY_STATUS_02.equals(userPermission.getApprovalStatus())){
                    userPermission.setStatus(CommonConstant.AUTH_APPLY_STATUS_CODE.AUTH_APPLY_STATUS_04);
                    userPermission.setStatusName(CommonConstant.AUTH_APPLY_STATUS_NAME.AUTH_APPLY_STATUS_NAME_REJECT);
                }
                userPermission =(XtzyUserPermission) BeanUtils.updateBean(userPermission);
                userPermissionMapper.updateByPrimaryKeySelective(userPermission);
            }

        } catch (Exception e) {
            log.error("扭转流程异常：" + e.getMessage());
            return false;
        }
        return true;
    }
}
